import json
import os
import re
import requests
import time
from typing import Dict, Optional, List

class PoemContentManager:
    def __init__(self, content_file="poem_contents.json"):
        self.content_file = content_file
        self.poem_contents = self.load_contents()
        
    def load_contents(self) -> Dict:
        """加载本地存储的诗词内容"""
        if os.path.exists(self.content_file):
            try:
                with open(self.content_file, "r", encoding="utf-8") as f:
                    return json.load(f)
            except (json.JSONDecodeError, IOError):
                return {}
        return {}
    
    def save_contents(self):
        """保存诗词内容到本地文件"""
        try:
            with open(self.content_file, "w", encoding="utf-8") as f:
                json.dump(self.poem_contents, f, ensure_ascii=False, indent=4)
        except IOError as e:
            print(f"保存诗词内容失败: {e}")
    
    def clean_poem_name(self, poem_name: str) -> str:
        """清理诗词名称，提取核心关键词用于搜索"""
        # 移除括号及其内容（作者信息等）
        name = re.sub(r'[（()）].*?[）)]', '', poem_name)
        # 移除多余的空格
        name = re.sub(r'\s+', '', name)
        return name.strip()
    
    def search_poem_online(self, poem_name: str) -> Optional[str]:
        """在线搜索诗词全文（模拟实现）"""
        # 这里可以对接真实的诗词API
        # 目前返回None，表示没有在线数据源
        # 如果需要添加新的诗词，请直接编辑 poem_contents.json 文件
        
        return None
    
    def get_poem_content(self, poem_name: str) -> Optional[str]:
        """获取诗词全文，优先从本地获取，如果没有则在线搜索"""
        # 清理诗词名称
        clean_name = self.clean_poem_name(poem_name)
        
        # 先从本地缓存查找
        if clean_name in self.poem_contents:
            return self.poem_contents[clean_name]
        
        # 如果本地没有，尝试在线搜索
        content = self.search_poem_online(poem_name)
        if content:
            # 保存到本地缓存
            self.poem_contents[clean_name] = content
            self.save_contents()
            return content
        
        return None
    
    def batch_update_poems(self, poem_list: List[tuple]) -> Dict[str, bool]:
        """批量更新诗词内容"""
        results = {}
        for num, name in poem_list:
            try:
                content = self.get_poem_content(name)
                results[name] = content is not None
                time.sleep(0.1)  # 避免过于频繁的请求
            except Exception as e:
                print(f"更新诗词 {name} 时出错: {e}")
                results[name] = False
        
        return results
    
    def search_local_poems(self, keyword: str) -> List[tuple]:
        """在本地诗词中搜索关键词"""
        results = []
        for poem_name, content in self.poem_contents.items():
            if keyword in poem_name or keyword in content:
                results.append((poem_name, content))
        return results
    
    def get_all_cached_poems(self) -> List[str]:
        """获取所有已缓存的诗词名称"""
        return list(self.poem_contents.keys())
    
    def clear_cache(self) -> bool:
        """清空本地缓存"""
        try:
            self.poem_contents = {}
            self.save_contents()
            return True
        except Exception as e:
            print(f"清空缓存失败: {e}")
            return False
    
    def export_to_file(self, filename: str) -> bool:
        """导出诗词内容到文件"""
        try:
            with open(filename, "w", encoding="utf-8") as f:
                for name, content in self.poem_contents.items():
                    f.write(f"\n{'='*50}\n")
                    f.write(f"诗名：{name}\n")
                    f.write(f"{'='*50}\n")
                    f.write(content)
                    f.write("\n")
            return True
        except Exception as e:
            print(f"导出文件失败: {e}")
            return False